# -*- coding: utf-8 -*-
# @Author: lim
# @Email: 940711277@qq.com
# @Date:  2018-03-01 14:45:22
# @Last Modified by:  lim
# @Last Modified time:  2018-03-30 15:19:01

import os
import time
import codecs
from config import SAVE_PATH
if not os.path.exists(SAVE_PATH):
    os.makedirs('data')


def covertLineToDict(line):
    """handle line date"""
    if '^' not in line:
        return
    idnum= name= phone =''
    con = line.split('^')
    for item in con: 
        if len(item) == 11 and item.isdigit() and item.startswith('1'):
            phone = item
        elif item[0:-1].isdigit() and (len(item)==15 or len(item)==18):
            idnum = item.replace('X','x')
        elif not item[:-1].isdigit():
            name = item
    pwd = idnum[-6:]

    return  {
        'idnum':idnum,
        'phone':phone,
        'name':name,
        'pwd':pwd
        }


def get_datetime():
    datetime = time.strftime("%Y-%m-%d*%H:%M:%S")
    return datetime


def get_time():
    return time.time()


def get_save_date():
    """写文件时间"""
    date = time.strftime("%Y-%m-%d")
    date = '_' + date
    return date


def get_crawl_date():
    """爬取时间"""
    date = time.strftime("%Y-%m-%d")
    return date


def channel_1(the_list):
    """连接插入 pg的表 1"""
    the_list.append(get_crawl_date())
    print the_list


def channel_2(the_list):
    """连接插入 pg的表 2"""
    the_list.append(get_crawl_date())
    print the_list


def channel_3(the_list):
    """连接插入 pg的表 3"""
    the_list.append(get_crawl_date())
    print the_list


def aes_1(field):
    """广州aes加密"""
    return field


def aes_2(field):
    """本地加密"""
    return field


def field_handle(field):
    """ 对字段去空格和^"""
    try:
        if field is None:
            field = ''
        if not isinstance(field,str):
            field = str(field)
        field = field.replace('^','')
        field = field.replace('\t','').replace(' ',''
                ).replace('\n','').replace('\r\n',''
                ).replace('\r','').strip()
        return field
    except:
        return ''


def save_file(filename,file,head):

    if not file or not filename:
        return
    try:     
        filename = filename+ get_save_date()+'.txt'
        filename = os.sep.join([SAVE_PATH,filename])
        if not os.path.exists(filename):
            with codecs.open(filename,'a','utf-8') as f:
                f.write(head+'\n')
        with codecs.open(filename,'a','utf-8') as f:
            f.write(file+'\n')
        return True
    except Exception as e:
        print(e)

